package com.laycoding.provider.registry;

import com.laycoding.common.util.IpUtils;
import com.laycoding.common.util.ZkUtils;
import com.laycoding.provider.handler.MyChannelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RpcRegistry {

    private Integer port;

    public RpcRegistry(Integer port) {
        this.port = port;
    }

    public void run() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            ServerBootstrap group = serverBootstrap.group(bossGroup, workGroup);
            group.channel(NioServerSocketChannel.class).childHandler(new MyChannelHandler())
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ZkRegistry zkRegistry = new ZkRegistry(ZkUtils.getClient());
            zkRegistry.doReginstry("/order/", IpUtils.getIp() + ":" + port, "rpcservice");
            //钩子函数
            Runtime.getRuntime().addShutdownHook(new RpcThread("/order/" + IpUtils.getIp() + ":" + port,zkRegistry));

            ChannelFuture channelFuture = serverBootstrap.bind(this.port).sync();
            System.out.println("RPC Registry start listen at " + this.port);
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
